<!--
 @description 经销商新建门店 编辑
 @fileName Edit.vue
 @author zengqiongying
 @created 2023-04-30 17:18:14
-->
<template>
  <div class="has-foot-pb">
    <Card>
      <DealerCell :detail="dealerData" />
      <FieldSelect
        v-model="formData.isOtherReceiveManagerKnow"
        title="是否需要其他业务客户经理接收知晓"
        :url="`/data-dict/app/v2/dictionary/BOOLEANS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        required
      />
      <template v-if="[1, '1'].includes(formData.isOtherReceiveManagerKnow)">
        <Cell
          v-if="dealerData.officeCode && detail.customerCode"
          :modelValue="formData.receiveManagerName"
          title="接收客户经理"
          placeholder="选择客户经理"
          :required="['1', 1].includes(formData.isOtherReceiveManagerKnow)"
          @right="onSearchCustomerManager"
        />

        <template v-if="!!formData.receiveManagerCode">
          <Cell :modelValue="formData.receiveManagerCode" title="接收客户经理编码" readonly />
          <Cell :modelValue="formData.receiveManagerTypeName" title="接收客户经理类型" readonly />
          <Cell :modelValue="formData.receiveManagerTel" title="接收客户经理电话" readonly />
        </template>
      </template>
      <Cell title="提报意见" is-column custom :right="false">
        <qmp-field v-model="formData.submitAnOpinion" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>
    <Card v-for="(item, i) in progressInfoItems" :key="i">
      <div class="editItem" @click.stop="toEditPage(item.code)">
        <qmp-circle
          :current-rate="item.rate"
          :rate="100"
          :speed="100"
          :text="`${item.rate}%`"
          :stroke-width="80"
          :size="58"
          :layer-color="item.rate === 0 ? '#FFF3DB' : '#E9ECEC'"
          :color="item.rate === 0 ? '#FFF3DB' : '#149774'"
        >
          <div class="text" :class="{ warning: item.rate === 0, normal: item.rate !== 0 }">{{ item.rate || 0 }}%</div>
        </qmp-circle>
        <div>
          <div class="name">{{ item.title }}</div>
          <div class="state">{{ item.info }}</div>
        </div>
        <qmp-icon class="icon" name="arrow" />
      </div>
    </Card>

    <div class="ctm-content-foot">
      <div class="btn radius-larg ctm-btn-warning" @click="onSave('B')">提交</div>
      <div class="btn radius-larg ctm-btn-main" @click="onView">预览</div>
      <div class="btn radius-larg ctm-btn-main" @click="onSave('A')">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick, computed } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import DealerCell from '@/components/DealerCell/index.vue'
  import { detail, getProgress, submitChange } from '@/apis/dealerMarketing/NewShop'
  import { createSave } from '@/apis/ctmCustomerChange'
  import { initFormData } from '@/utils'

  const none: any[] = [undefined, null, '']
  interface anyObjectModle {
    [key: string]: any
  }
  export default {
    name: 'DealerNewShopEdit',
    components: { Card, DealerCell, FieldSelect, Cell },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const $route = useRoute()
      const datas = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        detail: {},
        formData: {
          code: '', //单据编号
          isOtherReceiveManagerKnow: '0', //是否需要其他业务客户经理接收知晓
          receiveManagerCode: '', // 接收经理
          receiveManagerName: '',
          receiveManagerTel: '',
          receiveManagerTypeName: '',
          receiveManagerTypeCode: '',
          submitAnOpinion: ''
        },
        progressInfoItems: [
          {
            code: 'shop',
            title: '门店信息',
            info: '填写新门店信息',
            rate: 0
          },
          {
            code: 'address',
            title: '经销商收货地址',
            info: '有新增地址则要填写',
            rate: 0
          },
          {
            code: 'shopContacts',
            title: '门店联系人',
            info: '填写门店联系人信息',
            rate: 0
          },
          {
            code: 'reportPic',
            title: '门店报图情况',
            info: '填写门店装修报图',
            rate: 0
          },
          {
            code: 'handover',
            title: '经销商交接情况',
            info: '如果是交接才需要填写',
            rate: 0
          }
        ]
      })
      const dealerData = computed(() => {
        const d = { ...datas.detail }
        return {
          code: d.customerCode || '',
          name: d.customerName || '',
          officeCode: d.officeCode || '',
          officeName: d.officeName || '',
          createBy: d.createBy || ''
        }
      })
      const getDetail = () => {
        const id = `${datas.id}`
        detail(id).then((res) => {
          datas.detail = res.data || {}
          initFormData(res.data, datas.formData)
        })
        getProgress(id).then((res) => {
          const progressItems = datas.progressInfoItems
          if (res.data) {
            const d = res.data
            const rateObj: anyObjectModle = {
              shop: d.progressShop,
              address: d.progressAddress,
              shopContacts: d.progressShopContact,
              reportPic: d.progressReportPic,
              handover: d.progressHandover
            }
            datas.progressInfoItems = progressItems.map((v: any) => {
              let rate = rateObj[v.code] || 0
              return {
                ...v,
                ...{ rate }
              }
            })
          }
        })
      }

      const onSave = (schedule: string, callback: any) => {
        const data = {
          id: datas.id,
          schedule,
          ...datas.formData
        }
        if (schedule === 'B') {
          if (none.includes(data.isOtherReceiveManagerKnow)) {
            proxy.$toast('请选择是否需要其他业务客户经理接收知晓')
            return
          }
          if ([1, '1'].includes(data.isOtherReceiveManagerKnow)) {
            if (none.includes(data.receiveManagerCode)) {
              proxy.$toast('请选择接收客户经理')
              return
            }
          }
          const flag = datas.progressInfoItems.every((v: any) => v.rate === 100)
          if (!flag) {
            proxy.$toast('信息填写不完整，不能提交')
            return
          }
        }
        const FunctionName = schedule === 'B' ? submitChange : createSave
        FunctionName(data).then(() => {
          proxy.$toast(schedule === 'B' ? '提交成功' : '保存成功')
          proxy.$SimpleEvents.emit('refreshCustomerChangeItem', data.id)
          if (callback) {
            callback()
            return
          }
          nextTick(() => {
            $router.goBack()
          })
        })
      }

      const onView = () => {
        onSave('A', () => {
          $router.push({
            path: '/dealerNewShop/preview',
            query: {
              id: `${datas.id}`
            }
          })
        })
      }
      const toEditPage = (path: string) => {
        const { detail } = datas
        if (path === 'shopContacts' || path === 'reportPic') {
          if (!(detail.shopDTO && detail.shopDTO.id)) {
            proxy.$toast('未创建门店信息，不能操作')
            return
          }
        }
        $router.push({
          path: `/dealerNewShop/${path}`,
          query: {
            id: `${datas.id}`,
            changeCode: `${datas.detail.code}`
          }
        })
      }
      proxy.$SimpleEvents.registerEvent('refreshCustomerNewShopEditInfo', () => {
        console.log('刷新当前更改的变化')
        getDetail()
      })
      const onSearchCustomerManager = () => {
        const officeCode = dealerData.value.officeCode
        const customerCode = datas.detail.customerCode
        if ([undefined, null, ''].includes(officeCode)) {
          proxy.$toast('请先选择办事处')
          return
        }
        proxy.$SimpleEvents.registerEvent('NewShopAddSetManager', (data: any) => {
          onChangeReceiveManager(data)
        })
        $router.push({
          path: '/search/customerManager',
          query: {
            name: 'NewShopAddSetManager',
            office: officeCode,
            customer: customerCode
          }
        })
      }

      const onChangeReceiveManager = (d: any) => {
        const receiveManager = {
          receiveManagerCode: d?.personCode || '',
          receiveManagerName: d?.personName || '',
          receiveManagerTel: d?.personTel || '',
          receiveManagerTypeCode: d?.accountType || '',
          receiveManagerTypeName: d?.accountTypeName || ''
        }
        datas.formData = { ...datas.formData, ...receiveManager }
      }

      onBeforeRouteLeave((to, from) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['DealerInfoNewShop'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
      })

      getDetail()
      return {
        ...toRefs(datas),
        dealerData,
        onSave,
        onView,
        toEditPage,
        onSearchCustomerManager
      }
    }
  }
</script>
<style lang="less" scoped>
  .editItem {
    padding: 0 16px;
    position: relative;
    display: flex;
    align-items: center;
    /deep/ .qmp-circle {
      margin-right: 14px;
      .text {
        position: absolute;
        left: 0;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font: var(--font-main-body);
        &.normal {
          color: var(--texticon-color-brand-normal);
        }
        &.warning {
          color: var(--texticon-color-warning-normal);
        }
      }
    }
    .icon {
      position: absolute;
      right: 16px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 20px;
      color: var(--texticon-default-normal);
    }
    .name {
      font: var(--font-main-title-strengthen);
      color: var(--texticon-default-strong);
    }
    .state {
      margin-top: 2px;
      font: var(--font-main-body);
      color: var(--texticon-default-strong);
    }
  }
</style>
